<template>
    <div class="main-body">
        <div class="main">
            <el-card class="box-card">
                <el-tabs v-model="currentIndex" stretch @tab-change="handleTabsClick(currentIndex)">
                    <el-tab-pane label="登录" name="login" class="pane">
                        <el-form :model="loginForm" :rules="loginRules" status-icon ref="loginForm" label-position="right"
                            label-width="70px">
                            <div class="userNameOrEmailBox">
                                <el-select v-model="selectValue" placeholder="Select" @change="handleSelectChange"
                                    style="width: 120px;" :validate-event="false">
                                    <el-option label="用户名" value="username" />
                                    <el-option label="邮箱" value="email" />
                                </el-select>
                                <el-form-item :prop="selectValue === 'email' ? 'email' : 'username'" label-width="0" class="userNameOrEmailInput">
                                    <el-input type="text" v-model="loginForm[selectValue]"
                                        :placeholder="selectValue === 'email' ? '请输入邮箱' : '请输入用户名'" >
                                    </el-input>
                                </el-form-item>
                            </div>
                            <el-form-item label="密码" prop="password">
                                <el-input type="password" v-model="loginForm.password" />
                            </el-form-item>
                            <el-button type="primary" @click="login()" class="lineButton">登录</el-button>
                        </el-form>
                        <div>
                            <router-link to="/passwordResetting">
                                <el-button style="margin-top: 20px;" link>忘记密码</el-button>
                            </router-link>
                        </div>
                    </el-tab-pane>


                    <el-tab-pane label="注册" name="register">
                        <el-form :model="registerFormFirst" :rules="registerRulesFirst" status-icon ref="registerFormFirst"
                            label-position="right" label-width="70px" v-if="!userNameAndPasswordVerify">
                            <el-form-item label="用户名" prop="username">
                                <el-input type="text" v-model="registerFormFirst.username" />
                            </el-form-item>
                            <el-form-item label="昵称" prop="nickname">
                                <el-input type="text" v-model="registerFormFirst.nickname" />
                            </el-form-item>
                            <el-form-item label="密码" prop="password">
                                <el-input type="password" v-model="registerFormFirst.password" />
                            </el-form-item>
                            <el-form-item label="确认密码" prop="configurePassword">
                                <el-input type="password" v-model="registerFormFirst.configurePassword" />
                            </el-form-item>
                            <div>
                                <el-button type="primary" @click="checkUserNameAndPassword()" class="lineButton">确认</el-button>
                            </div>
                        </el-form>


                        <el-form :model="registerFormSecond" :rules="registerRulesSecond" status-icon ref="registerFormSecond"
                            label-position="right" label-width="70px" v-if="userNameAndPasswordVerify">
                            <el-form-item label="邮箱" prop="email">
                                <el-input type="text" v-model="registerFormSecond.email" />
                            </el-form-item>
                            <el-button type="primary" :disabled="getCaptchaButtonDisable" class="floatRight"
                                @click="getCaptchaByEmail()">{{ buttonText
                                }}</el-button>
                            <el-form-item label="验证码" prop="captcha">
                                <el-input type="text" v-model="registerFormSecond.captcha" />
                            </el-form-item>
                            <el-button type="primary" @click="register()" v-if="captchaGeted" class="lineButton">注册</el-button>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </el-card>
        </div>
    </div>
</template>
  
<script>
import {flowerUserLogin}  from "@/api/auth";
import { flowerUserRegister, flowerUserExistsTest  } from "@/api/flowerUser";
import { getCaptcha } from "@/api/email"
import { result } from "lodash";
import { ElMessage } from 'element-plus';
import router from '@/router/index'
import { jumpTo } from "@/utils/JumpDialog";
export default {
    data() {
        //验证规则
        var validateConfigurePassword = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请确认密码"));
            } else if (value !== this.registerFormFirst.password) {
                callback(new Error("两次密码不一致！"))
            } else {
                callback();
            }
        }
        return {
            currentIndex: "login",
            selectValue: "username",
            userNameAndPasswordVerify: false,

            //获取验证码按钮相关
            getCaptchaButtonDisable: false,
            buttonText: '获取验证码',
            remainingTime: 30,

            captchaGeted: false,

            loginForm: {
                username: null,
                password: "",
                email: null,
            },
            registerFormFirst: {
                username: "",
                password: "",
                nickname: "",
            },
            registerFormSecond: {
                email: "",
                captcha: "",
            },
            activeTab: "login",
            loginRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 6, max: 12, message: '用户名长度需要为6到12位', trigger: 'blur' },
                    { pattern: /^[a-zA-Z0-9]+$/, message: '用户名只能由数字、英文字母组成', trigger: 'blur' },
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                        type: 'email',
                        message: '请输入正确的邮箱格式',
                        trigger: ['blur', 'change']
                    },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,12}$/,
                        message: '密码需要同时包含英文字母和数字，且长度为8到12位',
                        trigger: 'blur'
                    }
                ],
                configurePassword: [
                    { validator: validateConfigurePassword, trigger: "blur", }
                ],

            },
            registerRulesFirst: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 6, max: 12, message: '用户名长度需要为6到12位', trigger: 'blur' },
                    { pattern: /^[a-zA-Z0-9]+$/, message: '用户名只能由数字、英文字母组成', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const params = {
                                username: value
                            };
                            flowerUserExistsTest(params).then(result => {
                                var findId = result.data.data
                                if (findId === 0) {
                                    callback()
                                }
                                else {
                                    callback("用户名已存在")
                                }
                            })
                        },
                        trigger: 'blur'
                    },
                ],
                nickname: [
                    { required: true, message: '请输入昵称', trigger: 'blur' },
                    { min: 1, max: 10, message: '昵称长度需要为1到10位', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,12}$/,
                        message: '密码需要同时包含英文字母和数字，且长度为8到12位',
                        trigger: 'blur'
                    }
                ],
                configurePassword: [
                    { validator: validateConfigurePassword, trigger: "blur", }
                ],
            },
            registerRulesSecond: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                        type: 'email',
                        message: '请输入正确的邮箱格式',
                        trigger: ['blur', 'change']
                    },
                    {
                        validator: (rule, value, callback) => {
                            const params = {
                                email: value
                            };
                            flowerUserExistsTest(params).then(result => {
                                var findId = result.data.data
                                if (findId === 0) {
                                    callback()
                                }
                                else {
                                    callback("邮箱已存在")
                                }
                            })
                        },
                        trigger: 'blur'
                    },
                ],
                captcha: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                ]
            }
        }
    },
    methods: {
        login() {
            this.$refs.loginForm.validate((valid) => {
                if (valid) {
                    //登录
                    console.log(this.loginForm)
                    flowerUserLogin(this.loginForm)
                        .then((response) => {
                            ElMessage.success("登录成功")
                            console.log(response.data);
                            //登录成功保存token
                            window.localStorage.setItem('token', response.data.data)
                            this.$router.push({name:'homeMain'})
                        })
                        .catch((error) => {
                            ElMessage.error(error.response.data.data)
                        })
                }
                else {
                    return;
                }
            });
        },
        register() {
            this.$refs.registerFormSecond.validate((valid) => {
                if (valid) {
                    //注册
                    const registerFrom = Object.assign({}, this.registerFormFirst, this.registerFormSecond)
                    return flowerUserRegister(registerFrom)
                        .then((response) => {
                            //注册成功
                            console.log(response)
                            ElMessage.success("注册成功")
                            jumpTo("注册成功","login",this.$route.name,3,"注册成功")
                        })
                        .catch((error) => {
                            ElMessage.error(error.response.data.data)
                        })
                }
                else {

                }
            })

        },
        handleSelectChange(value) {
            switch (value) {
                case "email":
                    this.loginForm.username = null
                    break
                case "username":
                    this.loginForm.email = null
                    break
            }
        },
        //当用户名密码昵称输入都正确后进入邮箱输入
        checkUserNameAndPassword() {
            this.$refs.registerFormFirst.validate((valid, error) => {
                if (valid) {
                    this.userNameAndPasswordVerify = true;
                }
                else {
                    console.log(error)
                }
            })
        },
        getCaptchaByEmail() {
            this.$refs.registerFormSecond.validateField('email', (valid) => {
                if (valid) {
                    // 如果没有错误消息，则表示 email 字段验证通过，可以执行获取验证码操作
                    const params = {
                        receiver: this.registerFormSecond.email
                    }
                    this.captchaGeted = true
                    this.getCaptchaButtonDisable = true
                    this.buttonText = `${this.remainingTime}秒后可再次发送`
                    let timer = setInterval(() => {
                        if (this.remainingTime > 1) {
                            this.remainingTime--
                            this.buttonText = `${this.remainingTime}秒后可再次发送`
                        } else {
                            this.getCaptchaButtonDisable = false
                            this.buttonText = '获取验证码'
                            this.remainingTime = 30
                            clearInterval(timer)
                        }
                    }, 1000)
                    getCaptcha(params)
                        .then((response) => {

                        })
                        .catch((error) => {
                            console.log(error);
                        })

                } else {
                    // 如果有错误消息，则表示 email 字段验证不通过
                }
            });
        },
        handleTabsClick(tab) {
            this.activeTab = tab;
        }
    },
    mounted:function(){

    }
};
</script>
<style scoped>
.main{
    /* position: absolute;
    margin-top: 77px;
    margin-left: 220px;
    height: 393px;
    width: 519px;
    background-color: #bc8775c4;
    border-radius: 18px; */
}
.main-body{
    display: flex;
    background-image: url(https://img1.baidu.com/it/u=3185065153,2560765855&fm=253&fmt=auto&app=138&f=JPEG?w=1200&h=500);
    background-repeat: no-repeat;
    background-size: 100%;
    /* margin-top: 14%; */
    background-position: center;
    justify-content: center;
    height: 642px;
}
.floatRight {
    float: right;
}


.box-card {
    position: relative;
    width: 388px;
    margin-top: 50%;
    background-color: #ffffff9e;
    border: none;
}

.userNameOrEmailBox {
    display: flex;
    width: 100%;
    margin-left: 15px;
}

.userNameOrEmailInput{
    width: 100%;
}

.lineButton {
    width: 100%;
}
</style>
  